<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<span>
				<el-select @change="handleChangeBrand()" v-model="queryParams.wtBrandName" class="zs-select-md zs-space-right-sm" placeholder="品牌" filterable>
					<el-option v-for="item in brandFirstBizTypes" :key="item.wtBrandName" :label="item.wtBrandName" :value="item.wtBrandName" />
				</el-select>
				<el-date-picker class="zs-space-right-sm" v-model="queryParams.startMonth" type="month" placeholder="权责开始月" value-format="YYYY-MM" @change="changeDate('start')" />
				<el-date-picker class="zs-space-right-sm" v-model="queryParams.endMonth" type="month" placeholder="权责结束月" value-format="YYYY-MM" @change="changeDate('end')" />
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': queryParams.chargeTypeCode.length > 0 }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<!-- <el-select :teleported="false" @change="queryList()" v-model="queryParams.contractsCode" class="zs-select-md zs-space-right-sm" placeholder="合同编号" filterable clearable>
							<el-option v-for="item in contractsCodeList" :key="item.contractsCode" :label="item.contractsCode" :value="item.contractsCode" />
						</el-select>
						<el-select :teleported="false" @change="queryList()" v-model="queryParams.conShopCode" filterable class="zs-select-md zs-space-right-sm" placeholder="单元编号" clearable>
							<el-option v-for="item in conShopCodeList" :key="item.conShopCode" :label="item.conShopCode" :value="item.conShopCode" />
						</el-select> -->
						<el-cascader :teleported="false" class="zs-select-md zs-space-right-sm" v-model="cascendCheck" :options="brandDownList" placeholder="费项" :props="cascaderProps" collapse-tags collapse-tags-tooltip clearable filterable:teleported="false" @change="changeCost" />
					</template>
				</el-popover>
				<el-button @click="queryList()" class="zs-btn-plain">查询</el-button>
			</span>
			<span>
				<el-button class="zs-btn-plain" @click="handleDownload">
					<el-icon class="el-icon--left"> <Upload /> </el-icon>导出
				</el-button>
			</span>
		</div>
		<div class="zs-card zs-table-page-content" :class="{'zs-table-first-row-special': queryParams.pageNum == 1}">
			<hsPageTable :loading="tableData.loading" :total="tableData.total" :tableData="tableData.data" :cloumns="tableData.cloumns" @pageChange="pageChange" :isHaveIndex="false" :cell-class-name="getCellClassName" :headerCellClass="getCellClassName"> </hsPageTable>
		</div>
	</div>
</template>

<script setup lang="jsx">
	import { downloadNewFile } from '@/utils/publicUtils';
	import { ElMessage } from 'element-plus';
	import { toThousands } from '@/utils/number-util';
	import { getBrandNameDropdownApi, getDropDownListApi, getConShopCodeDropdownApi, getContractsCodeDropdownApi, getBizModeDropdownApi, getContractsStatusDropdownApi } from '@/api/SpecialReport/receivable';
	import { getBondBillExportApi, getDepositBillListApi } from '@/api/SpecialReport/netReceipts';
	import { reactive, ref } from 'vue';
	import { useRoute } from 'vue-router';
	import { useStore } from 'vuex';
	let store = useStore();
	let route = useRoute();
	const curPageSize = ref(store.state.uiPageSizeDefault);
	const cascaderProps = { multiple: true, label: 'chargeTypeName', value: 'chargeTypeCode' };
	// 查询条件
	const cascendCheck = ref([]);
	let queryParams = reactive({
		projectCode: route.query.projectCode,
		invoiceCode: '',
		startMonth: '',
		endMonth: '',
		contractsStatus: [],
		pageNum: 1,
		chargeTypeCode: [],
		pageSize: curPageSize,
		conShopCode: '',
		contractsCode: '',
		wtBrandName: route.query.wtBrandName,
	});
	// 表格数据
	let tableData = reactive({
		loading: false,
		data: [],
		total: 0,
		cloumns: [
			{
				prop: 'index',
				label: '序号',
				width: '80',
				type: 'customMethods',
				methods: (a, empty, { $index }) => queryParams.pageNum == 1 ? ($index == 0 ? '合计' : $index + queryParams.pageSize * (queryParams.pageNum - 1)) : $index + 1 + queryParams.pageSize * (queryParams.pageNum - 1),
			},
			{ prop: 'financePeriod', label: '权责月份', width: '130', type: 'customMethods', methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'financePeriod') },
			{
				prop: 'wtBrandName',
				label: '品牌名称',
				align: 'left',
				type: 'customMethods',
				methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'wtBrandName'),
			},
			{
				prop: 'rentArea',
				label: '租赁面积',
				align: 'right',
				minWidth: '140',
				type: 'customMethods',
				methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'rentArea'),
			},
			{ prop: 'chargeTypeName', label: '费项名称', align: 'left', minWidth: '120', type: 'customMethods', methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'chargeTypeName') },
			{
				prop: 'invRecAmtL',
				label: '应收金额',
				align: 'right',
				minWidth: '140',
				type: 'customMethods',
				methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'invRecAmtL'),
			},
			{
				prop: 'invIncomeAmtL',
				label: '实收金额',
				align: 'right',
				minWidth: '140',
				type: 'customMethods',
				methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'invIncomeAmtL'),
			},
			{
				prop: 'debtAmt',
				label: '欠款金额',
				align: 'right',
				minWidth: '140',
				type: 'customMethods',
				methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'debtAmt'),
			},
			{ prop: 'invoiceLastDate', label: '最晚付款日', minWidth: '120', type: 'customMethods', methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'invoiceLastDate') },
			{ prop: 'debtTimeDiff', label: '欠款时间', minWidth: '110', type: 'customMethods', methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'debtTimeDiff') },
			{ prop: 'invoiceCode', label: '账单编号', minWidth: '120', type: 'customMethods', methods: (a, empty, { row, $index }) => rowMethods(row, $index, empty, 'invoiceCode') },
		],
	});
	function rowMethods(row, index, empty, key) {
		if (row[key]) {
			if (['rentArea', 'invRecAmtL', 'invRecAmtL', 'debtAmt', 'invrecamtl'].includes(key)) {
				return row[key] ? toThousands(Number(row[key]).toFixed(2)) : empty;
			} else {
				return row[key] || empty;
			}
		} else {
			if (index == 0) return '';
			return empty;
		}
	}

	const changeCost = () => {
		const LevelTwoId = [];
		cascendCheck.value.map(item => {
			LevelTwoId.push(item[1]);
		});
		queryParams.chargeTypeCode = LevelTwoId;
	};

	// 分页变化
	function pageChange(page) {
		queryParams.pageNum = page.current;
		queryParams.pageSize = page.pageSize;
		queryList();
	}

	let brandDownList = ref([]);
	async function getBrandDownList() {
		const res = await getDropDownListApi();
		let resData = res.data;
		if (resData.code == 200 && resData.data.categoryArrearsDropDownList != null) {
			brandDownList.value = resData.data.categoryArrearsDropDownList;
			// let arrType = [];
			// let arrTypeCode = [];
			// brandDownList.value.forEach(val => {
			// 	arrType = arrType.concat(val.children);
			// });
			// if (route.query.curCardTypeType == 1) {
			// 	arrType.forEach(item => {
			// 		if (item.arrearsLab == '1') {
			// 			arrTypeCode.push(item.chargeTypeCode);
			// 		}
			// 	});
			// } else if (route.query.curCardTypeType == 2) {
			// 	arrType.forEach(item => {
			// 		if (item.arrearsLab == '2') {
			// 			arrTypeCode.push(item.chargeTypeCode);
			// 		}
			// 	});
			// } else {
			// 	arrTypeCode = [];
			// }
			// cascendCheck.value = arrTypeCode;
			// queryParams.chargeTypeCode = arrTypeCode;
		} else {
			brandDownList.value = [];
		}
	queryList();

		// });
	}
	getBrandDownList();

	async function queryList() {
		if ((queryParams.startMonth && !queryParams.endMonth) || (!queryParams.startMonth && queryParams.endMonth)) {
			ElMessage.warning('请选择权责开始结束月份');
			return;
		}
		tableData.loading = true;
		let params = Object.assign({}, queryParams);
		const res = await getDepositBillListApi(params);
		let resData = res.data;
		if (resData.errorCode == 200 && resData.data.billList != null && resData.data.billList.length > 0) {
			if (queryParams.pageNum == 1) {
				let sumObj = {
					invRecAmtL: resData.data.invRecAmtLTotal,
					invIncomeAmtL: resData.data.invIncomeAmtLTotal,
					debtAmt: resData.data.debtAmtTotal,
				};
				resData.data.billList.unshift(sumObj);
			}
			tableData.data = resData.data.billList;
			tableData.total = resData.totalCount;
		} else {
			tableData.data = [];
			tableData.total = 0;
		}
		tableData.loading = false;
		// });
	}

	const getCellClassName = ({ columnIndex }) => {
		if ([3].includes(columnIndex)) {
			return 'zs-table-cell-border-right';
		}
	};

	function changeDate(type) {
		if (queryParams.startMonth && queryParams.endMonth) {
			if (type == 'start' && queryParams.startMonth > queryParams.endMonth) {
				ElMessage.warning('开始月份不能大于结束月份');
				queryParams.startMonth = '';
			} else if (type == 'end' && queryParams.endMonth < queryParams.startMonth) {
				ElMessage.warning('结束月份不能小于开始月份');
				queryParams.endMonth = '';
			}
		}
	}

	let brandFirstBizTypes = ref([]);
	let bizModeList = ref([]);
	let contractsStatusList = ref([]);
	let conShopCodeList = ref([]);
	// let invoiceCodeList = ref([]);
	let contractsCodeList = ref([]);
	function getBrandfirstBizType() {
		// 品牌
		getBrandNameDropdownApi({ projectCode: route.query.projectCode }).then(res => {
			let resData = res.data;
			if (resData.errorCode == 200) {
				brandFirstBizTypes.value = resData.data;
			}
		});
		// 资产类型
		getBizModeDropdownApi({ projectCode: route.query.projectCode }).then(res => {
			let resData = res.data;
			if (resData.errorCode == 200) {
				bizModeList.value = resData.data;
			}
		});
		// 合同状态
		getContractsStatusDropdownApi().then(res => {
			let resData = res.data;
			if (resData.errorCode == 200) {
				contractsStatusList.value = resData.data;
			}
		});
		// 单元编号
		getConShopCodeDropdownApi({ projectCode: route.query.projectCode }).then(res => {
			let resData = res.data;
			if (resData.errorCode == 200) {
				conShopCodeList.value = resData.data;
			}
		});
		getContractList();
	}
	getBrandfirstBizType();

	function handleChangeBrand() {
		getContractList();
		queryList();
	}

	function getContractList() {
		// 合同编号
		getContractsCodeDropdownApi({ projectCode: route.query.projectCode, wtBrandName: queryParams.wtBrandName }).then(res => {
			let resData = res.data;
			if (resData.errorCode == 200) {
				contractsCodeList.value = resData.data;
			}
		});
	}

	//导出
	const handleDownload = async () => {
		let params = Object.assign({}, queryParams);
		params.brandId = params.brandId || 'all';
		params.firstFormat = params.firstFormat || 'all';
		const fileName = `保证金统计表收款明细表.xls`;
		let fileData = await getBondBillExportApi(params);
		downloadNewFile(fileData.data, fileName);
	};
</script>

<style lang="scss" scoped>
	:deep(.el-table__row .zs-link) {
		cursor: pointer !important;
	}
</style>
